<script>
import {createProps} from '@/utils';
import FieldRegistry from '@/components/hhd/design/FormField/FieldRegistry';
import Constants from '@/components/hhd/design/FormEngine/Constants';
import RelationWrapper from '@comp/hhd/design/FormEngine/RelationWrapper/RelationWrapper.vue';

export default {
  name: 'FieldDelegate',
  props: {
    fieldConfig: createProps(Object),
    context: createProps(Object),
    formModel: createProps(Object),
    rowIndex: createProps(Number),
    rowId: createProps(String),
  },
  render() {
    if (!this.fieldConfig || !this.context) return undefined;
    let comp = FieldRegistry[this.fieldConfig.component];
    return comp && this.wrapRelation(this.renderField(comp)) || undefined;
  },
  methods: {
    wrapRelation(vnode) {
      let h = this.$createElement;
      return h(RelationWrapper, {
        props: {
          fieldConfig: this.fieldConfig,
          formModel: this.formModel,
          rowIndex: this.rowIndex,
          rowId: this.rowId,
          context: this.context
        }
      }, [vnode]);
    },
    renderField(comp) {
      if (this.formModel[Constants.authFieldName][this.fieldConfig.fieldName] === 'hide') return;
      return this.formModel && this.$createElement(comp, {
        props: {
          value: this.formModel[this.fieldConfig.fieldName],
          title: this.fieldConfig.fieldTitleName && this.formModel[this.fieldConfig.fieldTitleName] || undefined,
          auth: this.formModel[Constants.authFieldName][this.fieldConfig.fieldName],
          fieldConfig: this.fieldConfig,
          rowIndex: this.rowIndex,
          required: this.formModel[Constants.requiredFieldName][this.fieldConfig.fieldName]
        },
        class: {
          'form-field-required': this.formModel[Constants.requiredFieldName][this.fieldConfig.fieldName]
            && this.formModel[this.fieldConfig.fieldName] !== 0
            && !this.formModel[this.fieldConfig.fieldName],
        },
        on: {
          'update': () => this.context && this.context.formFieldUpdate && this.context.formFieldUpdate(this.fieldConfig, this.rowId),
          'update:value': v => this.formModel[this.fieldConfig.fieldName] = v,
          'update:title': t => this.fieldConfig.fieldTitleName && (this.formModel[this.fieldConfig.fieldTitleName] = t),
        }
      }) || undefined;
    },
  }
};
</script>